<template>
  <div>
    <a-select
      v-model:value="selectValue"
      v-bind="attrs"
      style="width: 100%"
      placeholder="请选择"
      option-label-prop="label"
      class="table-link-select"
      allowClear
      show-search
      options="selectOptions"
      :filter-option="false"
      :not-found-content="null"
      @search="handleSearch"
      @hange="handleChange"
    >
      <a-select-option v-for="item in options" :key="item.value" :value="item.value">
        <div v-if="!item.value && auths.add" class="opt-add" @click="(...args) => $setup.handleClickAdd && $setup.handleClickAdd(...args)">记录</div>
        <div v-else class="online-select-item">
          <div v-if="showImage" class="left-avatar" :style="getImageAsBackground(item)">
            <!-- <img v-if="getImageUrl(item)" src="getImageUrl(item)" alt="" /> -->
          </div>

          <div class="right-content">
            <div class="label">
              <EditOutlined v-if="auths.update" @click="handleClickEdit(e, item)" />
            </div>
            <div class="others">
              <Fragment v-for="(pro, index) in textFieldArray" :key="index">
                <div class="other-item ellipsis">item[pro]</div>
              </Fragment>
            </div>
          </div>
        </div>
      </a-select-option>
    </a-select>
    <!-- <online-pop-modal :id="popTableName" @register="registerPopModal" @success="getFormData" topTip="" /> -->
  </div>
</template>
<script lang="ts">
  import { ref, watch, computed, defineComponent } from 'vue';
  import { propTypes } from '/@/utils/propTypes';
  import { EditOutlined } from '@ant-design/icons-vue';
  import { useDebounceFn } from '@vueuse/core';
  import { useModal } from '/@/components/Modal';
  // import OnlinePopModal from '../../auto/comp/OnlinePopModal.vue';
  import { useLinkTable } from '../../use/useAutoForm';
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

  export default defineComponent({
    name: 'LinkTableSelect',
    components: {
      EditOutlined,
      // OnlinePopModal,
    },
    props: {
      valueField: propTypes.string.def(''),
      textField: propTypes.string.def(''),
      tableName: propTypes.string.def(''),
      multi: propTypes.bool.def(false),
      value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.array]),
      linkFields: propTypes.array.def([]),
      imageField: propTypes.string.def([]),
    },
    emits: ['change', 'update:value'],
    setup(props, { emit }) {
      const selectValue = ref([]);
      const {
        auths,
        mainContentField,
        textFieldArray,
        selectOptions,
        reloadTableLinkOptions,
        addQueryParams,
        formatData,
        initFormData,
        getImageAsBackground,
        showImage,
      } = useLinkTable(props);
      const [registerPopModal2, { openModal: openPopModal2 }] = useModal();
      const popTableName = computed(() => {
        return props.tableName;
      });
      const bindValue = computed(() => {
        if (props.multi === true) {
          return {
            mode: 'multiple',
          };
        } else {
          return {};
        }
      });
      function handleClickAdd(e) {
        e == null ? void 0 : e.stopPropagation();
        e == null ? void 0 : e.preventDefault();
        openPopModal2(true, {});
      }
      function handleClickEdit(e, record2) {
        e == null ? void 0 : e.stopPropagation();
        e == null ? void 0 : e.preventDefault();
        if (auths.update == false) {
          console.error('当前用户无编辑权限!');
          return;
        }
        openPopModal2(true, {
          isUpdate: true,
          record: record2,
        });
      }
      async function getFormData(data) {
        await reloadTableLinkOptions();
        const temp = data[props.valueField];
        selectValue.value = temp;
      }
      function handleSearch(text2) {
        addQueryParams(text2);
        reloadTableLinkOptions();
      }
      function handleChange(text2) {
        emitValue(text2);
        if (!text2) {
          addQueryParams();
          reloadTableLinkOptions();
        }
      }
      function emitValue(text2) {
        const formData = {};
        const linkFieldArray = props.linkFields;
        let textArray = [];
        if (!text2) {
          initFormData(formData, linkFieldArray);
        } else {
          const options = toRaw(selectOptions.value);
          console.log('options>>', options);
          const tempText = toRaw(text2);
          if (tempText instanceof Array) {
            textArray = [...tempText];
          } else {
            if (props.multi == true) {
              textArray = tempText.split(',');
            } else {
              textArray = [tempText];
            }
          }
          const arr = options.filter((i) => textArray.indexOf(i[props.valueField]) >= 0);
          if (arr && arr.length > 0) {
            let record2 = Object.assign({}, arr[0]);
            if (arr.length > 1) {
              for (let i = 1; i < arr.length; i++) {
                record2 = hebing(record2, arr[i]);
              }
            }
            const titleField = mainContentField.value;
            record2[titleField] = record2.label;
            initFormData(formData, linkFieldArray, record2);
          }
        }
        formatData(formData);
        emit('change', textArray.join(',') || '', formData);
        emit('update:value', textArray.join(',') || '');
      }
      function hebing(oldObj, newObj) {
        const record2 = {};
        Object.keys(oldObj).map((k) => {
          record2[k] = (oldObj[k] || '') + ',' + (newObj[k] || '');
        });
        return record2;
      }
      watch(
        () => props.value,
        async (val) => {
          if (val) {
            if (props.multi == true) {
              selectValue.value = val.split(',');
            } else {
              selectValue.value = val;
            }
            if (props.linkFields && props.linkFields.length > 0) {
              emitValue(val);
            }
          } else {
            selectValue.value = [];
          }
        },
        { immediate: true }
      );
      watch(
        () => selectOptions.value,
        (val) => {
          if (val && val.length > 0) {
            if (props.linkFields && props.linkFields.length > 0) {
              if (selectValue.value && selectValue.value.length > 0) {
                emitValue(selectValue.value);
              }
            }
          }
        }
      );
      
      return {
        selectValue,
        selectOptions,
        registerPopModal: registerPopModal2,
        popTableName,
        textFieldArray,
        handleClickAdd,
        handleClickEdit,
        getFormData,
        handleSearch: useDebounceFn(handleSearch, 800),
        handleChange,
        bindValue,
        showImage,
        getImageAsBackground,
        auths,
      };
    },
  });
</script>
<style scoped>
  .table-link-select .opt-add {
    cursor: pointer;
    font-size: 14px;
    color: #1565c0;
    margin: 3px 0;
    padding: 0 8px;
  }

  .table-link-select .online-select-item {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    cursor: pointer;
    position: relative;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    line-height: 22px;
    min-height: 56px;
    display: flex;
    padding: 6px 40px 6px 12px;
  }

  .table-link-select .online-select-item .left-avatar {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 44px;
    height: 44px;
    margin-right: 8px;
  }

  .table-link-select .online-select-item .left-avatar > img {
    width: 44px;
    height: 44px;
    border: 1px solid rgba(0, 0, 0, 0.06);
    border-radius: 4px;
  }

  .table-link-select .online-select-item .right-content {
    overflow: hidden;
    -webkit-flex: 1;
    flex: 1 1 0;
    -ms-flex: 1;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }

  .table-link-select .online-select-item .right-content .anticon-edit:hover {
    color: #0c8fcf;
  }

  .table-link-select .online-select-item .right-content .label {
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    display: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    color: #333;
    font-weight: 700;
    line-height: 1.5;
    margin-bottom: 4px;
  }

  .table-link-select .online-select-item .right-content .others {
    margin-left: -7px;
    box-sizing: border-box;
  }

  .table-link-select .online-select-item .right-content .others .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: top;
    white-space: nowrap;
  }

  .table-link-select .online-select-item .right-content .others .other-item {
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    border-right: 1px solid #9e9e9e;
    color: #757575;
    display: inline-block;
    height: 1.2em !important;
    line-height: 1em;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    padding: 0 7px;
  }
</style>
